package net.piggy.http;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.util.AttributeKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;

public class HttpClient {

    private final static Logger logger = LoggerFactory.getLogger(HttpClient.class);

    public static void send(FullHttpRequest request, Channel channel) throws InterruptedException {
        NioEventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group).channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            ChannelPipeline p = ch.pipeline();
                            p.addLast(new HttpClientCodec());
                            p.addLast(new HttpObjectAggregator(8192));
                            p.addLast(new ChannelInboundHandlerAdapter(){
                                @Override
                                public void channelRead(ChannelHandlerContext ctx, Object msg) {
                                    FullHttpResponse response = (FullHttpResponse) msg;
                                    logger.info("response body -> " + response.content().toString(io.netty.util.CharsetUtil.UTF_8));
                                    // 异步
                                    ChannelFuture channelFuture = channel.writeAndFlush(response);
                                    channelFuture.addListener((ChannelFutureListener) future -> {
                                        logger.info("response refCnt -> " + response.refCnt());
                                        Long start = (Long) future.channel().attr(AttributeKey.valueOf(Config.TIME)).get();
                                        long end = System.currentTimeMillis();
                                        long time =  end - start;
                                        logger.info("use time -> " + time + "ms");
                                    });
                                    ctx.close();
                                }
                                @Override
                                public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
                                    cause.printStackTrace();
                                    ctx.close();
                                }
                            });
                        }
                    });

            ChannelFuture future = bootstrap.connect(Config.getConfigParam().getTargetIp(), Config.getConfigParam().getTargetPort()).sync();
            future.channel().writeAndFlush(request).addListener((ChannelFutureListener) channelFuture -> {
                if (channelFuture.isSuccess()) {
                    logger.info("request send success");
                } else {
                    logger.info("request send failed");
                    channelFuture.cause().printStackTrace();
                }
            });
            ChannelFuture channelFuture = future.channel().closeFuture().sync();
            channelFuture.addListener((ChannelFutureListener) listener -> logger.info("request finish"));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();
        }
    }
}

